<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use api\utils\libs\DataScope;
use common\models\system\TestData;
use yii\db\ActiveQuery;

class TestDataController extends AuthController
{
    use CommonAction;

    protected string $model = TestData::class;
    protected bool $validate = true;

    protected function listBefore(array $params): array
    {
        return array_merge($params, ['debug' => 1]);
    }

    protected function listQuery(ActiveQuery $query): ActiveQuery
    {
        // 根据数据权限获取列表
        $scope = new DataScope($this->getUser());
        $query = $scope->queryDataScope($query->with('struct', 'user')->asArray());
        return $query;
    }

    /**
     * @param TestData $model
     * @param string $type
     * @param array $oldData
     * @return string
     * @throws \common\extend\exception\B5HttpException
     */
    protected function validateBefore(TestData $model, string $type, array $oldData): string
    {
        if ($type == 'add') {
            $user = $this->getUser();
            $struct = $user->struct;
            if (!$struct) return '无所属部门机构';
            $model->struct_id = $user->struct->id;
            $model->user_id = $user->id;
        } elseif ($type == 'edit') {
            $model->struct_id = $oldData['struct_id'];
            $model->user_id = $oldData['user_id'];
            if ($res = $this->checkPower($oldData['user_id'], $oldData['struct_id'])) {
                return $res;
            }
        }
        return '';
    }

    protected function deleteBefore(TestData $model, string $type): string
    {
        return $this->checkPower($model->user_id, $model->struct_id);
    }

    private function checkPower($user_id, $struct_id): string
    {

        $scope = new DataScope($this->getUser());
        if (!$scope->checkRowScope($user_id, $struct_id)) {
            return '无权限操作此数据';
        }
        return '';
    }
}
